package cn.wolfcode.controller;

import cn.wolfcode.anno.RequiredPermission;
import cn.wolfcode.domain.Department;
import cn.wolfcode.query.DepartmentQueryObject;
import cn.wolfcode.query.JsonResult;
import cn.wolfcode.query.PageResult;
import cn.wolfcode.service.IDepartmentService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/department")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    //处理所有请求
    //处理显示的请求
    @RequestMapping("/list")
    @RequiredPermission(name = "部门列表",expression = "department:list")
    public String list(Model model,DepartmentQueryObject q){
        PageInfo<Department> pageInfo = departmentService.query(q);
        model.addAttribute("pageResult", pageInfo);
        return "department/list";
    }
    //处理删除请求
    @RequiredPermission(name = "部门删除",expression = "department:delete")
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id){
        departmentService.delete(id);
        return new JsonResult();
    }
    //处理去修改和保存的请求
    @RequiredPermission(name = "部门保存或更新",expression = "department:saveOrUpdate")
    @RequestMapping("/input")
    public String input(Long id,Model model){
        if(id!=null){
            Department department = departmentService.selectOne(id);
            model.addAttribute("department", department);//回显
        }
        return "department/input";
    }
    //处理修改和保存的请求
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Department department){
        try {
            if(department.getId()!=null){
                departmentService.update(department);
            }
            else{
                departmentService.insert(department);
            }
            return new JsonResult("操作成功", true);
        } catch(Exception e) {
            e.printStackTrace();
            return new JsonResult("操作失败", false);
        }
    }
}